<template>
	<view>
		<view class="fix_menu">
			<view class="item" v-for="(item,index) in tab" :key="index" @click="get_list(item.type)">
				<text :class="type == item.type ? 'active' : ''">{{item.title}}</text>
			</view>
		</view>
		<view class="address_search">
			<u-search placeholder="搜索订单收件人姓名/手机号" v-model="keyword" :showAction="false"></u-search>
		</view>

		<view class="w100 order_list">
			<view v-if="list.length">
				<view class="w100 order_item mb20" v-for="(item, i) in list">
					<view class="w100 order_top">
						<view class="fl time">
							<text>{{ item.create_time }}</text>
						</view>
						<view class="fr status">
							<text>{{ item.status_name }}</text>
						</view>
					</view>
					<view class="w100 goods_list" @click="toDetail(item.order_id)">
						<view class="w100 item" v-for="items in item.children">
							<image :src="items.file_path" mode=""></image>
							<view class="fr item_msg">
								<view class="title">
									{{ items.goods_name }}
								</view>
								<view class="props">
									{{ items.goods_props.toString() }} ×{{ items.total_num }}
								</view>
								<view class="w100 price">
									<view class="b_price">
										<text class="sub">￥</text><text>{{ items.goods_price }}</text>
									</view>
								</view>
							</view>
						</view>
					</view>

					<view class="w100 pay_price">
						<text class="fl ep_text red_text"
							v-if="item.children[0].express_no">物流单号：{{ item.children[0].express_no }}</text>
						<view class="b_price">
							<text class="s_text">实付款：</text> <text class="sub">￥</text><text
								class="orderPrice">{{ item.pay_price }}</text>
						</view>
					</view>

					<view class="w100 goods_operate">
						<view class="btn-item onBtn" v-if="item.status_code == 10"
							@click.stop="payOrder(item.order_id)">去支付
						</view>
						<view class="btn-item onBtn" v-if="item.status_code == 30"
							@click.stop="orderReceipt(item.order_id)">确认收货
						</view>
						<view class="btn-item" v-if="item.status_code < 30" @click.stop="orderCancel(item.order_id)">
							取消订单
						</view>
						<view class="btn-item" v-if="item.status_code == 70 && item.children[0].is_comment == 0"
							@click.stop="toComment(item.order_id, item.children[0].order_goods_id)">去评价</view>
						<view class="btn-item onBtn"
							v-if="item.status_code >= 60 && !item.order_invoice_id && !item.refund_status"
							@click.stop="toInvoice(item.order_id)">申请开票</view>
						<view class="btn-item onBtn"
							v-if="item.status_code >= 60 && (item.state == 0 || item.state == 4)"
							@click.stop="toInvoiceDetail(item.order_invoice_id)">开票中</view>
						<view class="btn-item onBtn"
							v-if="item.status_code >= 60 && (item.state == 1 || item.state == 2)"
							@click.stop="toInvoiceDetail(item.order_invoice_id)">查看发票</view>


						<view class="t_check" :class="{'checked': item.checked}" @click.stop="order_select(i)"
							v-if="type == 1 && item.status_code == 10"></view>
					</view>
				</view>

				<view class="cart_fix" v-if="type == 1">
					<view class="fl">
						<view class="t_check" :class="allChecked && 'checked'" @click="cart_all_select"></view>
					</view>
					<view class="total_box">
						<view class="total_price">合计：<text>￥ {{ total.toFixed(2)  }}</text></view>
					</view>
					<view class="fr">
						<button class="p_btn sub_btn" @click="buyGoods">合并支付</button>
					</view>
				</view>
			</view>

			<view class="u-empty" v-else>
				<u-empty text="暂无数据"
					icon="https://tianliyx.oss-cn-shanghai.aliyuncs.com/images/20250311/0057423001741660320.png"></u-empty>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		watch,
		computed
	} from 'vue';
	import {
		onLoad,
		onShow,
		onReachBottom
	} from '@dcloudio/uni-app';
	import {
		COMMON
	} from "@/utils/commom.js"
	import {
		order_list,
		cancel_order,
		order_pay,
		confirm_receipt,
		multi_order_pay
	} from "@/api/order.js"

	const list = ref([]);
	const tab = ref([{
			title: '全部订单',
			type: 0
		},
		{
			title: '待付款',
			type: 1
		},
		{
			title: '待发货',
			type: 2
		},
		{
			title: '待收货',
			type: 3
		},
		{
			title: '待评价',
			type: 4
		}
	])
	const type = ref(0);
	const keyword = ref('');
	const p = ref(1);



	onLoad((option) => {
		type.value = option.type;
	})

	onShow(() => {
		get_list(type.value, keyword.value);
	})

	watch(() => keyword.value, (newVal) => {
		get_list(type.value, newVal)
	});

	// 监听上拉加载事件
	onReachBottom(() => {
		p.value++;
		order_list({
			type: type.value,
			key: keyword.value || '',
			p: p.value
		}).then(res => {
			let data = res.data;
			list.value = list.value.concat(data.list);
		})
	});

	//获取列表
	function get_list(t, key) {
		list.value = [];
		p.value = 1;
		type.value = t;
		order_list({
			type: t,
			key: key || '',
			p: 1
		}).then(res => {
			let data = res.data;
			list.value = data.list;
		})
	}


	// 存储选中的订单ID（使用Set自动去重）
	const selectedOrderIds = ref(new Set());

	// 总金额（使用number类型确保精度）
	const total = ref(0);

	// 计算属性：是否全选
	const allChecked = computed({
		get: () => {
			const selectableOrders = list.value.filter(item => item.status_code === 10);
			return selectableOrders.length > 0 &&
				selectableOrders.every(item => selectedOrderIds.value.has(item.order_id));
		},
		set: (value) => {
			const selectableOrders = list.value.filter(item => item.status_code === 10);
			if (value) {
				// 全选
				selectableOrders.forEach(item => {
					selectedOrderIds.value.add(item.order_id);
					item.checked = true;
				});
			} else {
				// 取消全选
				selectableOrders.forEach(item => {
					selectedOrderIds.value.delete(item.order_id);
					item.checked = false;
				});
			}
		}
	});

	// 精确计算总金额
	const calculateTotal = () => {
		// 使用reduce确保精度，避免浮点数计算问题
		total.value = Array.from(selectedOrderIds.value).reduce((sum, orderId) => {
			const order = list.value.find(item => item.order_id === orderId);
			return sum + (Number(order?.pay_price) || 0);
		}, 0);
	};

	// 监听选中订单变化，自动更新总金额
	watch(selectedOrderIds, () => {
		calculateTotal();
	}, {
		deep: true
	});

	// 单个订单选择/取消选择
	const order_select = (index) => {
		const order = list.value[index];
		if (order.status_code !== 10) return; // 只允许选择待支付订单

		if (selectedOrderIds.value.has(order.order_id)) {
			selectedOrderIds.value.delete(order.order_id);
			order.checked = false;
		} else {
			selectedOrderIds.value.add(order.order_id);
			order.checked = true;
		}
	};

	// 全选/反选
	const cart_all_select = () => {
		allChecked.value = !allChecked.value;
	};

	// 合并支付
	const buyGoods = () => {
		if (selectedOrderIds.value.size === 0) {
			COMMON.Toast(`请选择至少一个订单!`)
			return;
		}

		const orderIds = Array.from(selectedOrderIds.value);
		
		multi_order_pay(orderIds).then(res => {
			if (res.status) {
				COMMON.wxPay(res.data);
			} else {
				COMMON.Toast(res.msg)
			}
		})
	
	};



	//订单支付
	function payOrder(order_id) {
		order_pay(order_id).then(res => {
			if (res.status) {
				COMMON.wxPay(res.data);
			} else {
				COMMON.Toast(res.msg)
			}
		})
	}

	//确认收货
	function orderReceipt(order_id) {
		uni.showModal({
			content: '确认已收到商品吗？',
			success: function(res) {
				if (res.confirm) {
					confirm_receipt(order_id).then(res => {
						if (res.status) get_list(0);
						COMMON.Toast(res.msg)
					})
				}
			}
		});
	}

	//取消订单
	function orderCancel(order_id) {
		uni.showModal({
			content: '确定取消订单吗？',
			success: function(res) {
				if (res.confirm) {
					cancel_order(order_id).then(res => {
						if (res.status) get_list(0);
						COMMON.Toast(res.msg)
					})
				}
			}
		});
	}

	// 跳转订单详情
	function toDetail(order_id) {
		uni.navigateTo({
			url: `/pages/order/detail?order_id=${ order_id }`
		});
	}

	// 跳转到商品评价页面
	function toComment(order_id, order_goods_id) {
		uni.navigateTo({
			url: `/pages/comment/create?order_id=${ order_id }&order_goods_id=${ order_goods_id }`
		});
	}

	// 申请开票
	function toInvoice(order_id) {
		uni.navigateTo({
			url: `/pages/invoice/index?type=order&order_id=${ order_id }`
		});
	}

	// 查看发票
	function toInvoiceDetail(order_invoice_id) {
		uni.navigateTo({
			url: `/pages/invoice/detail?order_invoice_id=${ order_invoice_id }`
		});
	}
</script>

<style lang="scss" scoped>
	@import '@/static/css/order.scss';

	.fix_menu {
		width: 100%;
		text-align: center;
		overflow: hidden;
		border-bottom: 1px solid #eee;
		background-color: #fff;
		position: fixed;
		padding: 30rpx 0 0;
		top: 0;
		left: 0;
		z-index: 100;

		.item {
			float: left;
			width: 20%;
			color: #333;

			text {
				border-bottom: 2px solid transparent;
				display: table;
				padding-bottom: 10rpx;
				margin: auto;
			}

			.active {
				color: #f00;
				border-bottom: 2px solid #F00;
			}
		}
	}

	.address_search {
		background: #fff;
		position: fixed;
		top: 80rpx;
		left: 0;
		padding: 20rpx;
		width: 100%;
	}

	.order_list {
		padding: 200rpx 30rpx;

		.order_item {
			padding: 30rpx;
			border-radius: 10px;
			background: #fff;

			.goods_list {
				padding: 0;
				border-radius: 0;
				border-top: 1px solid #f2f2f2;
				border-bottom: 1px solid #f2f2f2;
			}

			.pay_price {
				padding: 15rpx 0;

				.b_price {
					float: right;

					.orderPrice {
						font-size: 32rpx;
					}
				}
			}

			.ep_text {
				font-size: 26rpx;
				padding-top: 6rpx;
			}

			.order_top {
				padding-bottom: 15rpx;

				.time {
					font-size: 28rpx;
					color: #666;
				}

				.status {
					font-size: 28rpx;
					color: #f00;
					font-weight: 600;
				}
			}


		}
	}
</style>